<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片上传测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .upload-section {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            margin-bottom: 30px;
            background-color: #fafafa;
            transition: border-color 0.3s;
        }
        .upload-section:hover {
            border-color: #409eff;
        }
        .upload-input {
            display: none;
        }
        .upload-btn {
            background-color: #409eff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        .upload-btn:hover {
            background-color: #66b1ff;
        }
        .file-info {
            margin-top: 20px;
            padding: 15px;
            background-color: #f0f9ff;
            border-radius: 4px;
            border-left: 4px solid #409eff;
        }
        .result-section {
            margin-top: 30px;
            padding: 20px;
            background-color: #f5f7fa;
            border-radius: 4px;
            border: 1px solid #e4e7ed;
        }
        .success {
            color: #67c23a;
            font-weight: bold;
        }
        .error {
            color: #f56c6c;
            font-weight: bold;
        }
        .uploaded-image {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #409eff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 10px;
            vertical-align: middle;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .tips {
            background-color: #e6f7ff;
            border: 1px solid #91d5ff;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
            color: #0050b3;
        }
        .api-test {
            margin-top: 30px;
            padding: 20px;
            background-color: #fff7e6;
            border: 1px solid #ffd591;
            border-radius: 4px;
        }
        .test-btn {
            background-color: #fa8c16;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .test-btn:hover {
            background-color: #ffa940;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🖼️ 图片上传功能测试</h1>
        
        <div class="tips">
            <strong>💡 提示：</strong>此页面用于测试商品管理中的图片上传功能。选择图片后，系统会自动上传到后端并返回URL地址。
        </div>

        <div class="upload-section">
            <input type="file" id="fileInput" class="upload-input" accept="image/jpeg,image/png" multiple>
            <button class="upload-btn" onclick="document.getElementById('fileInput').click()">
                📷 选择图片上传
            </button>
            <div id="fileInfo" class="file-info" style="display: none;">
                <strong>已选择的文件：</strong>
                <div id="fileList"></div>
            </div>
        </div>

        <div id="resultSection" class="result-section" style="display: none;">
            <h3>上传结果：</h3>
            <div id="resultContent"></div>
        </div>

        <div class="api-test">
            <h3>🔧 API接口测试</h3>
            <button class="test-btn" onclick="testConnection()">测试连接</button>
            <button class="test-btn" onclick="testGetProducts()">获取商品列表</button>
            <button class="test-btn" onclick="clearResults()">清空结果</button>
            <div id="apiResult" style="margin-top: 15px;"></div>
        </div>
    </div>

    <script>
        let selectedFiles = [];

        // 文件选择处理
        document.getElementById('fileInput').addEventListener('change', function(e) {
            selectedFiles = Array.from(e.target.files);
            displayFileInfo();
            
            if (selectedFiles.length > 0) {
                uploadFiles();
            }
        });

        // 显示文件信息
        function displayFileInfo() {
            const fileInfo = document.getElementById('fileInfo');
            const fileList = document.getElementById('fileList');
            
            if (selectedFiles.length === 0) {
                fileInfo.style.display = 'none';
                return;
            }

            fileInfo.style.display = 'block';
            fileList.innerHTML = '';

            selectedFiles.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.style.marginTop = '10px';
                fileItem.innerHTML = `
                    <strong>文件 ${index + 1}:</strong> ${file.name}<br>
                    <small>大小: ${formatFileSize(file.size)} | 类型: ${file.type}</small>
                `;
                fileList.appendChild(fileItem);
            });
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 上传文件
        async function uploadFiles() {
            const resultSection = document.getElementById('resultSection');
            const resultContent = document.getElementById('resultContent');
            
            resultSection.style.display = 'block';
            resultContent.innerHTML = '<div class="loading"></div> 正在上传图片...';

            const results = [];

            for (let i = 0; i < selectedFiles.length; i++) {
                const file = selectedFiles[i];
                
                // 验证文件
                if (!validateFile(file)) {
                    results.push({
                        success: false,
                        filename: file.name,
                        error: '文件验证失败，只能上传JPG/PNG格式且小于500KB的图片'
                    });
                    continue;
                }

                try {
                    const formData = new FormData();
                    formData.append('file', file);

                    const response = await fetch('/api/product/uploadImage', {
                        method: 'POST',
                        body: formData
                    });

                    const result = await response.json();
                    
                    if (result.status === 200 && result.data) {
                        results.push({
                            success: true,
                            filename: file.name,
                            url: result.data
                        });
                    } else {
                        results.push({
                            success: false,
                            filename: file.name,
                            error: result.message || '上传失败'
                        });
                    }
                } catch (error) {
                    results.push({
                        success: false,
                        filename: file.name,
                        error: error.message || '网络错误'
                    });
                }
            }

            displayResults(results);
        }

        // 验证文件
        function validateFile(file) {
            const isJPGPNG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt500K = file.size / 1024 < 500;
            return isJPGPNG && isLt500K;
        }

        // 显示结果
        function displayResults(results) {
            const resultContent = document.getElementById('resultContent');
            let html = '';

            results.forEach((result, index) => {
                if (result.success) {
                    html += `
                        <div style="margin-bottom: 20px; padding: 15px; background: #f0f9ff; border-radius: 4px; border-left: 4px solid #67c23a;">
                            <div class="success">✅ 上传成功: ${result.filename}</div>
                            <div style="margin-top: 10px;">
                                <strong>图片URL:</strong><br>
                                <code style="background: #e6f7ff; padding: 5px; border-radius: 2px; word-break: break-all;">${result.url}</code>
                            </div>
                            <div style="margin-top: 10px;">
                                <img src="${result.url}" class="uploaded-image" alt="上传的图片">
                            </div>
                        </div>
                    `;
                } else {
                    html += `
                        <div style="margin-bottom: 15px; padding: 15px; background: #fef0f0; border-radius: 4px; border-left: 4px solid #f56c6c;">
                            <div class="error">❌ 上传失败: ${result.filename}</div>
                            <div style="margin-top: 5px; color: #606266;">错误信息: ${result.error}</div>
                        </div>
                    `;
                }
            });

            resultContent.innerHTML = html;
        }

        // 测试连接
        async function testConnection() {
            const apiResult = document.getElementById('apiResult');
            apiResult.innerHTML = '<div class="loading"></div> 正在测试连接...';

            try {
                const response = await fetch('/api/product/uploadImage', {
                    method: 'OPTIONS'
                });
                
                apiResult.innerHTML = `
                    <div style="padding: 10px; background: #f0f9ff; border-radius: 4px; color: #67c23a;">
                        <strong>✅ 连接测试完成</strong><br>
                        状态: ${response.status} ${response.statusText}<br>
                        URL: ${response.url}
                    </div>
                `;
            } catch (error) {
                apiResult.innerHTML = `
                    <div style="padding: 10px; background: #fef0f0; border-radius: 4px; color: #f56c6c;">
                        <strong>❌ 连接测试失败</strong><br>
                        错误: ${error.message}<br>
                        请检查后端服务是否正常运行
                    </div>
                `;
            }
        }

        // 测试获取商品列表
        async function testGetProducts() {
            const apiResult = document.getElementById('apiResult');
            apiResult.innerHTML = '<div class="loading"></div> 正在获取商品列表...';

            try {
                const response = await fetch('/api/product/getAllProducts');
                const result = await response.json();
                
                if (result.status === 200) {
                    apiResult.innerHTML = `
                        <div style="padding: 10px; background: #f0f9ff; border-radius: 4px; color: #67c23a;">
                            <strong>✅ 获取商品列表成功</strong><br>
                            商品数量: ${result.data ? result.data.length : 0}<br>
                            消息: ${result.message || '成功'}
                        </div>
                    `;
                } else {
                    apiResult.innerHTML = `
                        <div style="padding: 10px; background: #fef0f0; border-radius: 4px; color: #f56c6c;">
                            <strong>❌ 获取商品列表失败</strong><br>
                            状态: ${result.status}<br>
                            消息: ${result.message || '未知错误'}
                        </div>
                    `;
                }
            } catch (error) {
                apiResult.innerHTML = `
                    <div style="padding: 10px; background: #fef0f0; border-radius: 4px; color: #f56c6c;">
                        <strong>❌ 获取商品列表失败</strong><br>
                        错误: ${error.message}<br>
                        请检查后端服务是否正常运行
                    </div>
                `;
            }
        }

        // 清空结果
        function clearResults() {
            document.getElementById('apiResult').innerHTML = '';
            document.getElementById('resultContent').innerHTML = '';
            document.getElementById('resultSection').style.display = 'none';
            selectedFiles = [];
            document.getElementById('fileInfo').style.display = 'none';
            document.getElementById('fileInput').value = '';
        }
    </script>
</body>
</html>